package com.amos.knife4j.config.exception.controller;

import com.amos.knife4j.config.exception.BusinessException;
import com.amos.knife4j.config.result.ResultEnums;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * controller异常统一处理
 *
 * @author meng_lbo
 * @date 2018/12/21  11:11
 */
@Component
@Aspect
public class ControllerExceptionAspect {
    private static final Logger log = LoggerFactory.getLogger(ControllerExceptionAspect.class);

    @Around("@annotation(com.amos.knife4j.config.exception.controller.ControllerExceptionHandler)")
    public Object handControllerMethodHandle(ProceedingJoinPoint pjp) {
        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();
            try {
                logHandle(pjp, request);
            } catch (Exception e) {
                log.error("参数获取异常", e);
            }
            //处理
            if (throwable instanceof BusinessException) {
                log.error("controller:" + throwable.getMessage());
                throw (BusinessException) throwable;
            } else {
                //记录异常日志
                log.error("controller:" + throwable.getMessage(), throwable);
                throw new BusinessException(ResultEnums.ERROR);
            }
        }
    }

    private void logHandle(ProceedingJoinPoint pjp, HttpServletRequest request) {
        String resource = request.getHeader("user-agent");
        log.error("客户端信息:" + resource);
        String os = request.getHeader("App-OS");
        String version = request.getHeader("version");
        log.error("异常源:" + os + version);
        String str = "";
        for (Object s : pjp.getArgs()) {
            str += s + ",";
        }
        String token = request.getHeader("ticket");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("ticket");
        }
        log.error("异常参数:" + str + ",token:" + token);
    }


}